<template>
  <div class="container">
    <div class="box">
      <el-form
        :model="loginForm"
        ref="loginRef"
        :rules="loginRules"
        label-width="80px"
      >
        <el-form-item prop="username" label="账号">
          <el-input
            v-model="loginForm.username"
            prefix-icon="el-icon-user-solid"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            v-model="loginForm.password"
            type="password"
            prefix-icon="el-icon-user-solid"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="loginBtn">
        <el-button type="primary" @click="loginValid">登录</el-button>
        <el-button type="success" @click="resetForm()">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 表单的验证规则（加在form-item上，而不是input上）
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetForm() {
      console.log(this)
      this.$refs.loginRef.resetFields()
      this.loginForm = {}
    },
    loginValid() {
      this.$refs.loginRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          this.$message.error('请输入正确信息')
        } else {
          const { data: res } = await this.$http.post('login', this.loginForm)
          // console.log(res)
          if (res.meta.status !== 200) {
            this.$message.error('账号密码错误')
          } else {
            this.$message.success('登录成功')
            window.sessionStorage.setItem('token', res.data.token)
            this.$router.push('/home')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.loginBtn {
  display: flex;
  justify-content: center;
}
.container {
  background-color: lightblue;
  height: 100%;
}
.box {
  width: 400px;
  height: 300px;
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.el-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 70px;
}
</style>
